package JAVA300.第十二章网络编程;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 客户端中的接收端
 * 1。接收消息
 * 2。释放资源
 * 3。run
 */

public class web_TCPChatReceive implements Runnable{


    private DataInputStream dis=null;
    private Socket socket;
    private boolean isRunning;
    public web_TCPChatReceive(Socket socket) {
        this.socket = socket;
        this.isRunning = true;

        try {
            dis = new DataInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //读
    //接收数据
    private String receive(){

        String getMsg ="";//避免空指针
        try {

            getMsg=  dis.readUTF();
            return getMsg;
        //    System.out.println("run here!");
         //   msg = getMsg.split(":");

        } catch (IOException e) {
            System.out.println("---error Client receive2-----");
            release();
        }

        return getMsg;
    }

    //释放资源-释放资源-借助带有可变参数的工具类函数进行封装
    private void release(){
        this.isRunning = false;
        web_TCPChatUntils.close(dis,socket);

    }

    @Override
    public void run() {
        while (isRunning){
            String getMsg = receive();
            if (!getMsg.equals("")){

                System.out.println(getMsg);
            }
//            String[] datas = getMsg.split("&");
//            for (String info:datas){
//                String[] usrinfo = info.split("=");
//
//                if (usrinfo[0].equals("uname")){
//                    username = usrinfo[1];
//                }else if(usrinfo[0].equals("upwd")){
//                    userpwd = usrinfo[1];
//                }
//
//            }
        }

    }
}
